<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-4-11
 * Time: 上午11:01
 * 产品审核
 * 状态：0正常1禁止销售2仅零售3仅分销销售4仅直属下级销售5仅所有者销售6已废弃8未通过9未审核
*/
namespace pft\Verify;
class Verify {
    protected $ErrArr = array('errcode'=>1003,'msg'=>'执行SQL语句失败,请联系网站管理员');
    protected $SucArr = array('errcode'=>1000,'msg'=>'更新成功');
    private $pid;
    private $did;
    public function __construct($pid,$did=''){
        $this->pid = $pid;
        $this->did = $did;
    }

    public function SetSceneryStatues($landid,$status) {
        $str = "UPDATE uu_land SET status='{$status}' WHERE id={$landid}";
        if($GLOBALS['le']->query($str)) {
            return $this->SucArr;
        }
        return $this->ErrArr;
    }

    /**
     * 获取产品审核结果
     * @param $pid 产品总表ID
     * @param $did 分销商ID
     * @return array
     */
    public function GetVerifyResult() {

        $str = "SELECT e.id,e.cln,e.msg FROM uu_product_ext e "
            ."LEFT JOIN uu_products p ON e.pid=p.id  "
            ."WHERE e.pid={$this->pid} AND  p.p_status=8  AND e.status=0";
        //echo $str;
        $GLOBALS['le']->query($str);
        $results = array();
        while($rows = $GLOBALS['le']->fetch_assoc()) {
            $results = $rows;
        }
        return $results;
    }

    /**
     * 添加审核记录
     * @param $cln 未通过审核字段
     * @param $msg 原因
     * @return array
     */
    public function RefuseVerify($cln,$msg,$modify_op,$verify_id=null) {
        if($this->ChkExist()) {
            $str = "UPDATE  uu_product_ext SET cln='{$cln}',msg='{$msg}',"
                ."status=0 WHERE pid={$this->pid} AND did={$this->did}";
        }
        else {
            $str = "INSERT INTO uu_product_ext SET cln='{$cln}',"
                ."msg='{$msg}',pid={$this->pid},did={$this->did}";
        }
        if(!empty($verify_id)) {
            $this->UpdateVerify($modify_op,$verify_id);
        }
        //echo $str;
        //$this->SetModifyOp($modify_op,$tbl);
        if($GLOBALS['le']->query($str)) {
            //if(!$e) {
                $str = "UPDATE uu_products SET apply_limit=2,verify_op={$modify_op} WHERE id={$this->pid}";
                $GLOBALS['le']->query($str);
            //}
            return array('errcode'=>1000,'msg'=>'审核成功');
        }
        return $this->ErrArr;
    }

    public function ChkExist() {
        $str = "SELECT COUNT(*) AS c FROM uu_product_ext WHERE pid={$this->pid} AND did={$this->did}";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f('c');
    }

    /**
     * 获取产品销售范围
     * @return int
     */
    private function _getProvideTo() {
        $chkStr = 'SELECT p_status FROM uu_products WHERE id=' . $this->pid . ' LIMIT 1';
        //echo $chkStr;
        $GLOBALS['le']->query($chkStr);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f('p_status');
    }

    /**
     * 产品审批通过操作
     * @params int $modify_op 审核人员ID
     * @params int $verify_id
     * @params string  $modify_oper 审核人姓名
     * @return array
     *      2013-09-04 14:08:38更新：如果产品是现场支付且供应商未开启现场支付功能，则只有供应商及该供应商下级可以销售
     *      2013-09-13 17:57:00更新：更改审核状态的字段为apply_limit(0未审核1通过2拒绝)，新增_getProvideTo()方法
     *
     * 批量价格配置oid机构ID,tid产品ID,app配置机构范围(0除供应商机构外1供应商机构2仅供应商3仅直属下级)
     * release($oid,$tid,$app=0)
     * uu_products p_status 0与3执行2次 第一次1 第二次0  4执行一次 传3  5执行1次  传2
     */
    public function PassProduct($modify_op,$verify_id=null,$modify_oper=null) {
        $appto = $this->_getProvideTo();//销售范围
        //$price_tpm_set = array(0,3,4,5);//价格模板套用
        $price_tpl_set = array(0=>1,3=>1,4=>3,5=>2);//价格模板套用
        $strChk = "SELECT l.status,l.id,t.pay FROM uu_land l,uu_jq_ticket t "
                ." WHERE l.id=t.landid and t.pid={$this->pid} LIMIT 1";
        //echo $strChk;
        $GLOBALS['le']->query($strChk);
        $GLOBALS['le']->fetch_assoc();
        $lstate = $GLOBALS['le']->f('status');
        $landid = $GLOBALS['le']->f('id');
        $payinf = $GLOBALS['le']->f('pay'); // 支付方式0景区现付，1在线支付

        if(!$lstate) {
            $this->SetSceneryStatues($landid,1);
            $logword = date('Y-m-d H:i:s'). "|ID为[{$landid}]的产品被审核通过|操作人:{$modify_oper}";
            Log::writeLog($logword, Log::SYSOPT_LOG_PATH);
        }

        //如果是新产品，然后调用价格模板程序——问柯航
        if(!$this->_isNewProduct()) {
            //为了新产品在未配置的情况下也能销售。。。
            $str_get_oid = "SELECT oid,pay_on_spot FROM uu_distributor WHERE id=".$this->did;
            $GLOBALS['le']->query($str_get_oid);
            $GLOBALS['le']->fetch_assoc();
            $oid = $GLOBALS['le']->f('oid');
            //echo $str_get_oid;
            $pay_on_spot = $GLOBALS['le']->f('pay_on_spot');

            $errArr = array(0=>'没产品ID',2=>'分销价拿不到',3=>'零售价拿不到',
                4=>'插入价格失败',5=>'更新模板失败');
            $price_res1 = release( $oid, $this->pid, $price_tpl_set[$appto]);//成功返回1，失败0
//            echo 'r1=' .$price_res1;
            if($price_res1!=1) return array('errcode'=>'1007',
                'msg'=>"产品价格配置错误1，请联系柯航.错误返回：{$price_res1},
                错误原因:{$errArr[$price_res1]},输入参数：oid={$oid}，pid={$this->pid}");

            if( $appto==0 || $appto==3 && $oid!=0) {
//                echo $payinf
                switch ($payinf) {
                    case 0:
                        $rflag = $pay_on_spot == 1 ? 1 : 0 ;
                        break;
                    case 1:
                        $rflag = $oid>0 && $oid != 37 ? 1 : 0;
                        break;
                    default:
                        $rflag = 1;
                        break;
                }
                if( $rflag ) {
                    //update:2013年9月29日10:16:23，“全站套用”
                    $price_res2 = release( $oid, $this->pid);//成功返回1，失败0
//                    echo 'r2=' . $price_res2;
                    if($price_res2!=1) return array('errcode'=>'1007',
                        'msg'=>"产品价格配置错误1，请联系柯航.错误返回：{$price_res2},
                错误原因:{$errArr[$price_res2]},输入参数：oid={$oid}，pid={$this->pid}");
                }
            }
        }



        $str = "UPDATE uu_products SET apply_limit=1,verify_op={$modify_op} WHERE id={$this->pid} LIMIT 1";
        //echo $str;
        $GLOBALS['le']->query($str);
        if(!empty($verify_id)) {
            $this->UpdateVerify($modify_op,$verify_id);
        }


        if(!$this->ChkExist()) {
            return $this->SucArr;
        }
        $str = "UPDATE uu_product_ext SET status=1 WHERE pid={$this->pid} AND did={$this->did} LIMIT 1";
        //echo $str;
        if($GLOBALS['le']->query($str)) {
            return $this->SucArr;
        }
        return $this->ErrArr;
    }

    /**
     * 获取最新产品修改未审核的记录
     * @return mixed
     */
    public function GetVerifyOne() {
        $str = "SELECT * FROM uu_prod_verify WHERE pid={$this->pid} AND oper=0 ORDER BY created_at DESC LIMIT 1";
        $GLOBALS['le']->query($str);
        $result = $GLOBALS['le']->fetch_assoc();
        return $result;
    }

    /**
     * 获取产品修改记录列表
     * @return array
     */
    public function GetVerifyList() {
        $str = "SELECT * FROM uu_prod_verify WHERE pid={$this->pid} ORDER BY created_at DESC";
        //echo $str;
        $GLOBALS['le']->query($str);
        $lists = array();
        while($rows = $GLOBALS['le']->fetch_assoc()) {
            $lists[] = $rows;
        }
        return $lists;
    }

    /**
     * 更新产品修改记录的审核人员及时间
     * @param $id 主键ID
     * @param $oper 审核人员
     * @return mixed
     */
    public function UpdateVerify($oper, $id) {
        $str = "UPDATE uu_prod_verify SET oper={$oper},verified_at=now() WHERE id={$id} LIMIT 1";
        return $GLOBALS['le']->query($str);
    }

    /**
     * 验证是否存在修改记录,如果存在该产品ID记录且已有人审核，则不是新产品
     * @param $pid
     * @return mixed
     */
    private function _isNewProduct() {
        $str = "SELECT COUNT(*) AS c FROM uu_priceset WHERE tid={$this->pid} AND aid=0";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f('c');
    }

    /**
     * 生成修改记录
     * @param $pid 产品总表ID
     * @param $did 分销商ID
     * @param $state_old 变更前的数据
     * @param $state_new 变更后的数据
     * @param $ctype 更新类型1上架，2下架，3涨价，4降价，5总库存变更（131008）,6审核
     * @return mixed
     */
    static function LogVerify($pid,$did,$chg_old,$chg_new,$oper=null,$ctype=0 ) {
        $str = "INSERT INTO uu_prod_verify SET pid={$pid},did={$did},chg_old='{$chg_old}',cgh_new='{$chg_new}',created_at=now(),ctype={$ctype}";
        if(!empty($oper)) {
            $str .= ",oper={$oper},verified_at=now()";
        }
//        echo $str;
        $GLOBALS['le']->query($str);
        return mysql_insert_id();
    }
}